package top.jiug.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.jiug.file.common.tools.UUidUtils;
import top.jiug.file.config.GetConfig;
import top.jiug.file.entity.SecretKey;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 文件 - 控制器
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private GetConfig getConfig;

    @GetMapping(value = "/findSecretKey")
    public JSONObject findSecretKey() {
        JSONObject jsonObject = new JSONObject();
        List<SecretKey> secretKeys= new ArrayList<>();
        for(String secretKey : getConfig.getFileSecretKeyMap().keySet()){
            secretKeys.add(new SecretKey(getConfig.getFileSecretKeyMap().get(secretKey),secretKey));
        }
        jsonObject.put("secretKeys", secretKeys);
        return jsonObject;
    }

    /**
     * 上传文件
     */
    @PostMapping("/fileUpload")
    public JSONObject fileUpload(@RequestParam("file") MultipartFile file, @RequestParam("secretKey") String secretKey) {

        JSONObject jsonObject = new JSONObject();

        String pathSuffix = getConfig.getFileSecretKeyMap().get(secretKey);
        if (pathSuffix==null||pathSuffix.equals("")) {
            jsonObject.put("code",400);
            jsonObject.put("message","无效密钥");
            return jsonObject;
        }

        JSONObject data = uploadFileAndPath(file, pathSuffix + "/");

        jsonObject.put("code",200);
        jsonObject.put("data",data);

        return jsonObject;
    }

    /**
     * 文件上传 指定路径
     * @param file 文件
     * @param path 上传服务器路径
     */
    public JSONObject uploadFileAndPath(MultipartFile file, String path) {
        JSONObject jsonObject = new JSONObject();
        try {
            //数据校验
            if (file == null) {
                jsonObject.put("code",400);
                jsonObject.put("message","文件为空");
                return jsonObject;
            }

            String originalFilename = file.getOriginalFilename();

            String[] split = null;
            if (originalFilename != null && originalFilename.contains(".")) {
                split = originalFilename.split("\\.");
            }
            // 文件后缀名
            String extension = split == null ? "" : split[split.length - 1];
            String fileName = UUidUtils.uuid() + "." + extension;
            //预判断文件夹是否存在，不存在则创建
            File dir = new File(getConfig.getBasePath()+path);
            if(!dir.exists()){
                dir.mkdirs();
            }
            //准备目标路径
            File dest = new File(getConfig.getBasePath()+path, fileName);
            file.transferTo(dest);
            jsonObject.put("url", getConfig.getDomain()+path+fileName);
            jsonObject.put("fileName", fileName);
            jsonObject.put("extension", extension);
            jsonObject.put("filePath", path);
            jsonObject.put("originalFilename", originalFilename);


            return jsonObject;
        } catch (IOException e) {
            log.error("上传文件失败", e);
            jsonObject.put("code",400);
            jsonObject.put("message","上传文件失败");
            return jsonObject;
        }
    }

    /**
     * 文件上传并压缩 1000 (仅支持图片压缩 )
     * @param file 文件
     * @param path 上传服务器路径
     */
    public JSONObject uploadFileCompress(MultipartFile file, String path) {

        JSONObject jsonObject = new JSONObject();

        try {
            //数据校验
            if (file == null) {
                jsonObject.put("code",400);
                jsonObject.put("message","文件为空");
                return jsonObject;
            }

            String originalFilename = file.getOriginalFilename();

            String[] split = null;
            if (originalFilename != null && originalFilename.contains(".")) {
                split = originalFilename.split("\\.");
            }
            // 文件后缀名
            String extension = split == null ? "" : split[split.length - 1];
            String uuid = UUidUtils.uuid();
            String fileName = uuid + "." + extension;
            //预判断文件夹是否存在，不存在则创建
            File dir = new File(getConfig.getBasePath()+path);
            if(!dir.exists()){
                dir.mkdirs();
            }
            //准备目标路径
            File dest = new File(getConfig.getBasePath()+path, fileName);
            file.transferTo(dest);

            //图片压缩
            Integer length = 1000;
            String newFileName = uuid + "_" + length + "." + extension;
            Thumbnails.of(getConfig.getBasePath() + path + fileName)
                    .size(length, length)
                    .toFile(getConfig.getBasePath() + path + newFileName);
            fileName = newFileName;
            //一次压缩不达标，再次达标
            File resultFile = new File(getConfig.getBasePath() + path, fileName);
            if (resultFile.exists() && resultFile.length() > 1048576) {//压缩后的文件大于1MB，继续压缩
                length = 600;
                newFileName = uuid + "_" + length + "." + extension;
                Thumbnails.of(getConfig.getBasePath() + path + fileName)
                        .size(length, length)
                        .toFile(getConfig.getBasePath() + path + newFileName);
                fileName = newFileName;
            }
            jsonObject.put("url", getConfig.getDomain()+path+fileName);
            jsonObject.put("fileName", fileName);
            jsonObject.put("extension", extension);
            jsonObject.put("filePath", getConfig.getBasePath()+path);
            jsonObject.put("doMain", getConfig.getDomain()+path);

        } catch (IOException e) {
            jsonObject.put("code",400);
            jsonObject.put("message","上传文件失败");
        }

        return jsonObject;
    }


}
